# app.py  商品推荐初步版本
from flask import Flask, jsonify, request
from data_loader import DataLoader
from recommender import Recommender
from flask_cors import CORS  # 确保从 flask_cors 导入 CORS

app = Flask(__name__)
CORS(app)  # 允许跨域请求，默认允许所有来源的请求
@app.route('/recommend', methods=['GET'])
def recommend():
    # 获取请求的参数
    username = request.args.get('username')  # 获取用户名参数
    top_n = request.args.get('top_n', default=6, type=int)  # 默认推荐 6 个商品

    # 加载用户购买数据
    data_loader = DataLoader()
    df = data_loader.get_user_purchase_data() #这个只是获取购买记录表的数据


    # 实例化 Recommender 类并获取推荐商品
    recommender = Recommender(df)  #这个就是在推荐算法当中构建用户商品矩阵以及计算商品之间的相似度

    if not username:
        # 如果没有提供用户名，推荐购买最多的商品
        recommendations = recommender.get_top_n_recommendations(username=None, top_n=top_n)
    else:
        # 如果提供了用户名，基于用户的购买历史进行推荐
        recommendations = recommender.get_top_n_recommendations(username=username, top_n=top_n)

    # 打印推荐结果
    print(f"Recommendations for {username if username else 'most popular'} (Top {top_n}): {recommendations}")
    # 返回推荐商品列表

    goods_sn_list=recommendations
    goods_info_df = data_loader.get_goods_info_by_goods_sn(goods_sn_list)
    data_loader.close_connection()
    #return jsonify({"username": username, "recommended_goods": recommendations})

 # 检查查询结果并返回数据
    if goods_info_df is not None and not goods_info_df.empty:
        # 转换为字典格式并返回
        goods_info_list = goods_info_df.to_dict(orient='records')
        return jsonify({"username": username,"goods_info": goods_info_list})
    else:
        return jsonify({"error": "No goods found for the provided goods_sn list"}), 404

if __name__ == '__main__':
    app.run(debug=True)